package com.lg.erp.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lg.erp.entity.*;
import com.lg.erp.service.IRoleMenuService;
import com.lg.erp.service.IRoleService;
import com.lg.erp.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ligen
 * @since 2021-04-12
 */
@RestController
public class RoleController {

    @Autowired
    private IRoleService roleService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IRoleMenuService roleFunService;
    //查所有
    @RequestMapping("/roles")
    public JsonResult findAllRole(){
        List<SRole> list = roleService.list();
        return new JsonResult(1,"ok",list);
    }
    //分页查
    @RequestMapping("/roles/{current}")
    public JsonResult findRoleByPage(@PathVariable Integer current){
        Page<SRole> page=new Page<>(current,10);
        IPage<SRole> pages = roleService.getRoleByPage(page);
        return new JsonResult(1,"ok",pages);
    }
    //存
    @RequestMapping(value = "/roles",method = RequestMethod.POST)
    public JsonResult saveRole(@RequestBody SRole role){
            SUser one = userService.getUserByLogin();
            role.setRoleCreateName(one.getRealName());
            role.setRoleCreateDate( new Timestamp(System.currentTimeMillis()));
            roleService.save(role);
            return new JsonResult(1,"创建成功",role);
    }
    //修改
    @RequestMapping(value = "/roles",method = RequestMethod.PUT)
    public JsonResult updateRole(@RequestBody SRole role){
            SUser one = userService.getUserByLogin();
            role.setRoleUpdateName(one.getRealName());
            role.setRoleUpdateDate(new Timestamp(System.currentTimeMillis()));
            roleService.updateById(role);
            return new JsonResult(1,"更新成功",role);

    }
    @RequestMapping(value = "/roles/{id}",method = RequestMethod.DELETE)
    public JsonResult removeRole(@PathVariable("id") String id){
        roleService.removeById(id);
        List<SRoleMenu> roleFunList = roleFunService.list(new QueryWrapper<SRoleMenu>()
                .lambda().eq(SRoleMenu::getRoleId, id));
        for (SRoleMenu roleFun : roleFunList) {
            roleFunService.remove(new QueryWrapper<SRoleMenu>().lambda()
                    .eq(SRoleMenu::getMenuId,roleFun.getMenuId())
                    .eq(SRoleMenu::getRoleId,roleFun.getRoleId()));
        }
        return new JsonResult(1,"删除成功",id);
    }
}
